package com.framework.projectframework.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Request上下文工具类
 */
@Slf4j
public class RequestContext {

    private final static String USER_REQUEST_TOKEN = "authorization";
    private final static String UNKNOWN_STR = "unknown";

    /**
     * 从Header中获取token
     */
    public static String getRequestHeaderToken() {
        HttpServletRequest request = getRequest();
        String header = request.getHeader(USER_REQUEST_TOKEN);
        // todo 默认token
        if (StringUtils.isBlank(header)) header = "0123ca4e07f3443d9754630374e11e08";
        if (StringUtils.isBlank(header)) {
            throw new RuntimeException("");
        }
        return header;
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取ip
     */
    public static String getRealRemoteAdrr() {
        String ip = getRequest().getHeader("x-forwarded-for");

        log.debug("x-forwarded-for = {}", ip);
        if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("Proxy-Client-IP");
            log.debug("Proxy-Client-IP = {}", ip);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("WL-Proxy-Client-IP");
            log.debug("WL-Proxy-Client-IP = {}", ip);
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
            ip = getRequest().getRemoteAddr();
            log.debug("RemoteAddr-IP = {}", ip);
        }
        if (!StringUtils.isEmpty(ip)) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}
